package com.whyl.eems.common.oss.ali.ram;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class StsService {

    private static final Logger logger = LoggerFactory.getLogger(StsService.class);

    /**
     * 阿里云OSS STS 认证配置
     *
     * 官方描述：
     *  通过STS服务，
     *  您所授权的身份主体（RAM用户、RAM用户组或RAM角色）可以获取一个自定义时效和访问权限的临时访问令牌。
     *
     *  相比RAM更加安全，具体还得看业务需求
     */

    /**
     * 详情查询：
     * https://help.aliyun.com/document_detail/66053.html?spm=a2c4g.11186623.6.766.77f732895H2EsM
     */
    public static final String REND_POINT = "sts.cn-hangzhou.aliyuncs.com";
    /**
     * 权限AK
     */
    private String accessKeyId = "LTAI8JCpBM5kdCfW";
    private String accessKeySecret = "ouu494hjTqz0nUC9z6VfKIL7bUoCxT";

    /**
     * 以下参数具体详情请查看：
     * https://help.aliyun.com/document_detail/28763.html?spm=a2c4g.11186623.6.771.7b9a3356HbvWc4
     */
    private String roleArn = "acs:ram::1415200880377934:role/aliyunosstokengeneratorrole";
    private String roleSessionName = "alice";
    private Long durationSeconds = 3600L;
    private String policy = "{\n" +
            "    \"Version\": \"1\", \n" +
            "    \"Statement\": [\n" +
            "        {\n" +
            "            \"Action\": [\n" +
            "                \"oss:*\"\n" +
            "            ], \n" +
            "            \"Resource\": [\n" +
            "                \"acs:oss:*:*:*\" \n" +
            "            ], \n" +
            "            \"Effect\": \"Allow\"\n" +
            "        }\n" +
            "    ]\n" +
            "}";

    /**
     * System.out.println("Expiration: " + response.getCredentials().getExpiration());
     * System.out.println("Access Key Id: " + response.getCredentials().getAccessKeyId());
     * System.out.println("Access Key Secret: " + response.getCredentials().getAccessKeySecret());
     * System.out.println("Security Token: " + response.getCredentials().getSecurityToken());
     * System.out.println("RequestId: " + response.getRequestId());
     *
     * @return
     */
    public AssumeRoleResponse getToken() {
        try {
            // 构造 default profile（参数留空，无需添加 region ID）
            IClientProfile profile = DefaultProfile.getProfile("", accessKeyId, accessKeySecret);
            // 用 profile 构造 client
            DefaultAcsClient client = new DefaultAcsClient(profile);
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setRoleArn(roleArn);
            request.setRoleSessionName(roleSessionName);
            request.setEndpoint(this.REND_POINT);
            // 设置过期时间
            request.setDurationSeconds(durationSeconds);
            request.setPolicy(policy); // Optional
            final AssumeRoleResponse response = client.getAcsResponse(request);

            // 缓存操作
//            response.getCredentials();

            return response;
        } catch (ClientException e) {
            logger.error("阿里云OSS 错误信息：Error code: " + e.getErrCode() + "Error message: " + e.getErrMsg() + "RequestId: " + e.getRequestId());
            return null;
        }
    }
}